package state

import (
	"alex/ptp1588boundaryclock/datatypes"
	"time"
)

type Clock struct {
	//Quality *datatypes.ClockQuality
	TimeStamp *datatypes.TimeStamp
	tickChannel chan bool
	tickTimeChannel chan uint8
	TimeStampChannel chan chan datatypes.TimeStamp
	tickTimeInMilliseconds uint8
	Milliseconds uint64
}

// Initializes the channel of the clock
func (c* Clock) Init() {
	//c.Quality = quality
	c.tickChannel = make(chan bool)
	c.tickTimeChannel = make(chan uint8)
	c.tickTimeInMilliseconds = uint8(1)
	c.Milliseconds = 0
	go c.tick()
	go c.Run()
}

// runs the clock
func (c* Clock) Run() {
	for {
		select {
		case <-c.tickChannel:
			c.Milliseconds++
		case newTick := <-c.tickTimeChannel:
			c.tickTimeInMilliseconds = newTick
		case t := <-c.TimeStampChannel:
			c.computeTimeStamp()
			t <- *c.TimeStamp

		}
	}
}

func (c* Clock) computeTimeStamp() {
	c.TimeStamp.SecondsField = c.Milliseconds / 1000
	c.TimeStamp.NanosecondsField = uint32((c.Milliseconds - c.TimeStamp.SecondsField*1000) * 1000)
}

func (c* Clock) tick() {
	for {
		time.Sleep(time.Duration(c.tickTimeInMilliseconds) * time.Millisecond)
		c.tickChannel <- true
	}
}

